package net.xiaohanlin.smartmetric.metricname;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

public class MetricNameService {
	public static MetricNameService INSTANCE = new MetricNameService();

	private ConstVariableNames constVariableNames;
	private Map<String, String> aliasNameMap = null;

	private MetricNameService() {
		this.aliasNameMap = new HashMap<>();
		this.constVariableNames = new ConstVariableNames();
	}

	public String getMetricName(Enum<?> cpu) {
		String name = cpu.name();
		String aliasName = aliasNameMap.get(name);
		return aliasName == null ? name : aliasName;
	}

	public String getMetricName(String name) {
		return name;
	}

	public String getHostIp() {
		return constVariableNames.ip;
	}

	public String getHostName() {
		return constVariableNames.hostName;
	}

	public String getPid() {
		return constVariableNames.pid;
	}

	public String replaceVariables(String str) {
		return this.constVariableNames.replaceVariables(str);
	}

	private static class ConstVariableNames {
		HashMap<String, String> constVariableValues;
		String ip;
		String hostName;
		String pid;

		String replaceVariables(String str) {
			if (str == null) {
				return null;
			}

			for (Map.Entry<String, String> entry : this.constVariableValues.entrySet()) {
				str = str.replaceAll(entry.getKey(), entry.getValue());
			}
			return str;
		}

		ConstVariableNames() {
			this.constVariableValues = new HashMap<>();
			try {
				InetAddress localHost = InetAddress.getLocalHost();
				this.ip = getHostIp(localHost);
				this.pid = String.valueOf(getPid());
				this.hostName = getHostName(localHost);
				this.constVariableValues.put("\\{ip\\}", getHostIp(localHost));
				this.constVariableValues.put("\\{hostName\\}", getHostName(localHost));
				this.constVariableValues.put("\\{pid\\}", this.pid);
			} catch (UnknownHostException e) {
				throw new ExceptionInInitializerError(e);
			}
		}

		public static int getPid() {
			RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
			String name = runtime.getName();
			return Integer.parseInt(name.substring(0, name.indexOf("@")));
		}

		public static String getHostIp(InetAddress netAddress) {
			if (null == netAddress) {
				return null;
			}
			String ip = netAddress.getHostAddress(); // get the ip address
			return ip;
		}

		public static String getHostName(InetAddress netAddress) {
			if (null == netAddress) {
				return null;
			}
			String name = netAddress.getHostName(); // get the host address
			return name;
		}

	}

}
